package com.bensonbasement.snorflux.jythonsupport;

import java.util.HashMap;

import org.python.core.Py;
import org.python.core.PyException;
import org.python.core.PyObject;

public class FlexPyObject extends PyObject {

	private final HashMap<String,PyObject> dict = new HashMap<String,PyObject>();
	
	@Override
	public PyObject __findattr_ex__(String name) {
		if (this.dict.containsKey(name)) {
			return this.dict.get(name);
		}
		else {
			return super.__findattr_ex__(name);
		}
	}
	
	@Override
	public void __setattr__(String name, PyObject value) {
		try {
			super.__setattr__(name, value);
		}
		catch (PyException ex) {
			if (ex.type == Py.AttributeError) {
				// TODO: Cheap hack!
				String errorMessage = ex.value.asString();
				if (errorMessage.contains("object has no attribute '"+name+"'")) {
					this.dict.put(name, value);
				}
				else {
					throw ex;
				}
			}
			else {
				throw ex;
			}
		}
	}
	
	@Override
	public void __delattr__(String name) {
		if (this.dict.containsKey(name)) {
			this.dict.remove(name);
		}
		else {
			super.__delattr__(name);
		}
	}
}
